﻿#include "ds_additem.h"
#include "ui_ds_additem.h"

DS_AddItem::DS_AddItem(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DS_AddItem)
{
    ui->setupUi(this);

    table=P_DATASOURCE;

    ui->host->setText("localhost");
    ui->port->setText("3306");
    ui->dbName->setText("test");
}

DS_AddItem::~DS_AddItem()
{
    delete ui;
}

bool DS_AddItem::addItem(const QString &entry,
                         const QString &host,
                         int port,
                         const QString &user,
                         const QString &password,
                         const QString &dbName)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (entry,host,port,user,passwd,db) "
                          "values (?,?,?,?,?,?)")
                  .arg(table));
    query.addBindValue(entry);
    query.addBindValue(host);
    query.addBindValue(port);
    query.addBindValue(user);
    query.addBindValue(password);
    query.addBindValue(dbName);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}


void DS_AddItem::on_btn_submit_clicked()
{
    QString entry=ui->entry->text().trimmed();
    if(entry.isEmpty())
        return;

    QString host=ui->host->text().trimmed();
    if(host.isEmpty())
        host="localhost";

    int port;
    QString portStr=ui->port->text().trimmed();
    if(portStr.isEmpty())
        port=3306;
    else {
        port=portStr.toInt();
        if(port == 0)
            port=3306;
    }

    QString user=ui->user->text().trimmed();
    if(user.isEmpty())
        user="root";

    QString passwd=ui->passwd->text().trimmed();
    if(passwd.isEmpty())
        return;

    QString dbName=ui->dbName->text().trimmed();
    if(dbName.isEmpty())
        dbName="test";

    if(addItem(entry,host,port,user,passwd,dbName))
        accept();
    else
        MESSAGE_CANNOT_SUBMIT
}
